﻿namespace Contacts.Maui.Mods
{
    class ContactRepository
    {
        public static List<Contact> _contacts = new List<Contact>()
        {
            new Contact(1,"John Doe","JohnDoe@gmail.com","416-800-8000","New York"),
            new Contact(2,"Jane Doe","JaneDoe@gmail.com","","New York"),
            new Contact(3,"Tom Hanks","TomHanks@gmail.com","","New York"),
            new Contact(4,"Frank Liu","FrankLiu@gmail.com","","New York"),
        };

        public static List<Contact> GetContacts() => _contacts;

        public static Contact GetContactById(int contactId)
        {
            return _contacts.FirstOrDefault(x => x.ContactId == contactId);
        }

        public static void UpdateContact(int contactId,Contact contact)
        {
            if(contact.ContactId!= contact.ContactId)
            {
                return;
            }
            var oldContact = GetContactById(contactId);
            if(oldContact != null)
            {
                oldContact = contact;
            }
        }

        public static void CreateContact(Contact contact)
        {
            var maxId = _contacts.Max(x => x.ContactId);
            contact.ContactId = maxId+1;
            _contacts.Add(contact);
        }

        public static void DeleteContact(int contactId) 
        {
            var contact = _contacts.FirstOrDefault( x => x.ContactId == contactId);
            if (contact == null)
            {
                return;
            }
            _contacts.Remove(contact);
        }

        public static List<Contact> SearchContacts(string filterText)
        {
            var contacts = _contacts.Where(x =>!string.IsNullOrWhiteSpace(x.Name) && x.Name.StartsWith(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
            if(contacts == null || contacts.Count <= 0)
            {
                contacts = _contacts.Where(x => !string.IsNullOrWhiteSpace(x.Email) && x.Email.StartsWith(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            else
            {
                return contacts;
            }
            if (contacts == null || contacts.Count <= 0)
            {
                contacts = _contacts.Where(x => !string.IsNullOrWhiteSpace(x.Phone) && x.Phone.StartsWith(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            else
            {
                return contacts;
            }
            if (contacts == null || contacts.Count <= 0)
            {
                contacts = _contacts.Where(x => !string.IsNullOrWhiteSpace(x.Address) && x.Address.StartsWith(filterText, StringComparison.OrdinalIgnoreCase)).ToList();
            }
            else
            {
                return contacts;
            }
            return contacts;
        }


    }
}
